<template>
  <div class="p-3  d-flex flex-column my-container">
    <div class="" v-if="permersion.search">

      <el-form :model="searchModel" :inline="true" class="d-flex justify-content-end">
        <el-form-item>
          <el-input v-model="searchModel.userName" clearable
                    @clear="searchClick" :disabled="detailsDisabled" placeholder="请输入用户姓名"
                    prefix-icon="el-icon-search"/>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchModel.status" placeholder="请选择状态">
            <el-option v-for="item in selectOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="searchClick">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="col d-flex flex-column shadow p-3 rounded-lg">
      <div class="mb-3">
        <el-button type="primary" icon="el-icon-plus" @click="handlerAccount" v-permission="'USER_ADD'"
                   v-if="permersion.add">新建账户
        </el-button>
        <el-button type="success" icon="el-icon-refresh" @click="refresh">刷新</el-button>
      </div>
      <div class="col d-flex over-auto">
        <el-table v-loading="loading" border :data="tableData" height="100%" ref="tableRef">
          <el-table-column type="index" label="序号" width="50" align="center"/>
          <el-table-column prop="userName" label="用户姓名" align="center"/>
          <el-table-column prop="roleName" label="角色名称" align="center"/>
          <el-table-column prop="accountPhone" label="登陆账号" align="center" width="100"/>
          <el-table-column prop="isFirst" label="是否为初始密码" align="center" width="130">
            <template slot-scope="{ row }">
              <span v-if="row.isFirst == 1">是</span>
              <span v-else>否</span>
            </template>
          </el-table-column>
          <el-table-column prop="accountType" label="正常/停用状态" align="center" width="130">
            <template #default="{ row }">
              <span v-if="row.status == 1" style="color: #07c160">正常</span>
              <span v-else>停用</span>
            </template>
          </el-table-column>

          <el-table-column prop="createByName" label="创建人" align="center"></el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="170">
            <template slot-scope="scope">
              {{ scope.row.createTime }}
            </template>
          </el-table-column>
          <el-table-column prop="updateByName" label="更新人" align="center"></el-table-column>
          <el-table-column label="更新时间" align="center" prop="createTime" width="170">
            <template slot-scope="scope">
              {{ scope.row.updateTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="550" align="center">
            <template #default="{ row }">
              <!-- <el-button type="primary" size="mini" @click="handlerDetails(row)"
                >详情</el-button
              > -->
              <el-button type="warning" size="mini"
                         :disabled="(row.userCode == userCode) || (row.userCode.includes('ADMC'))"
                         v-permission="'USER_EDIT'" @click="handlerEdit(row)">编辑
              </el-button>
              <el-button type="danger" size="mini"
                         :disabled="(row.userCode == userCode) || (row.userCode.includes('ADMC'))"
                         v-permission="'USER_RESTPWD'" @click="handlerReset(row)">
                重置密码
              </el-button>
              <div class="status" v-permission="'USER_PROHIBIT'">
                <el-button type="success" size="mini"
                           :disabled="(row.userCode == userCode) || (row.userCode.includes('ADMC'))"
                           @click="handlerStatus(row)"
                           v-if="row.status == '0'">启用
                </el-button>
                <el-button type="danger" size="mini"
                           :disabled="(row.userCode == userCode) || (row.userCode.includes('ADMC'))"
                           @click="handlerStatus(row)"
                           v-else>禁用
                </el-button>
              </div>
              <el-button type="danger" size="mini"
                         :disabled="(row.userCode == userCode) || (row.userCode.includes('ADMC'))"
                         v-permission="'USER_DEL'" @click="handlerDelete(row)">删除
              </el-button>
              <el-button type="primary" size="mini" v-permission="'USER_DEL'" @click="handlerConfigMenu(row)">分配大屏菜单</el-button>
              <el-button type="primary" size="mini" v-permission="'USER_DEL'" @click="handlerConfigAppMenu(row)">分配APP菜单</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination class="pagination" :total="count" :page.sync="pageIndex" :limit.sync="pageSize"
                  @pagination="pagination"/>
    </div>

    <!-- 弹框 -->
    <yc-dialog ref="ycDialog" :centerTitle="centerTitle">
      <template #content>
        <div class="dialog-content">
          <el-form ref="loginFormRef" :rules="rules" :model="newAccountModel" label-width="90px">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="newAccountModel.userName" :disabled="detailsDisabled"/>
            </el-form-item>
            <el-form-item label="角色名称" prop="roleCode">
              <el-select style="width: 100%;" v-model="newAccountModel.roleCode" :disabled="detailsDisabled">
                <el-option v-for="item in userData" :key="item.roleCode" :label="item.roleName"
                           :value="item.roleCode"/>
              </el-select>
            </el-form-item>
            <el-form-item label="手机号码" prop="accountPhone">
              <el-input type="number" v-model="newAccountModel.accountPhone" :disabled="detailsDisabled"/>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>

    <!-- 分配大屏菜单 -->
    <yc-dialog ref="configDialog" :dialogTitle="dialogTitle" :show-center="false">
      <template #content>
        <div class="dialog-content">
          <div v-for="(item, index) in roleButtonList" :key="index" class="mb-3">
            <el-checkbox
              @change="(val) => handleCheckAllListChange(val, item)"
              :indeterminate="itemIndeterminate(item)"
              v-model="item.checkAll"
            >{{ item.menuTitle }}
            </el-checkbox>
            <el-checkbox-group
              v-model="checkedData"
              @change="handleCheckedCitiesChange"
              style="padding-left: 30px;">
              <el-checkbox
                class="mt-3"
                v-for="items in item.menuList"
                :key="items.menuCode"
                :label="items"
              >{{ items.menuName }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSaveConfig">确定</el-button>
        <el-button @click="$refs.configDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 分配APP菜单 -->
    <yc-dialog ref="configAppDialog" :dialogTitle="dialogTitle" :show-center="false">
      <template #content>
        <div class="dialog-content">
          <div v-for="(item, index) in roleButtonList2" :key="index" class="mb-3">
            <el-checkbox
              @change="(val) => handleCheckAllListChange2(val, item)"
              :indeterminate="itemIndeterminate2(item)"
              v-model="item.checkAll"
            >{{ item.menuTitle }}
            </el-checkbox>
            <el-checkbox-group
              v-model="checkedData2"
              @change="handleCheckedCitiesChange2"
              style="padding-left: 30px;">
              <el-checkbox
                class="mt-3"
                v-for="items in item.menuList"
                :key="items.menuCode"
                :label="items"
              >{{ items.menuName }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSaveConfigApp">确定</el-button>
        <el-button @click="$refs.configAppDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>
    
    <!-- 封装操作后弹框 -->
    <global-message v-if="isGlobalMessageShow" @receive="receive" :message="message"/>
  </div>
</template>

<script>
  import {
    queryAccountPage,
    updateLAccount,
    ResetPassword,
    deleteAccount,
    deactivate,
    insertUser,
    queryRole,
    queryMenuListWithTitle,
    setMenuAccountRelationShip,
    queryMenuListWithTitleByApp,
    setMenuAccountRelationShipByApp
  } from "@/api/userControl/account"
  import ycDialog from "@/components/pageDialog"

  export default {
    components: {
      ycDialog
    },
    data() {
      return {
        userCode: "",
        userData: [],
        isGlobalMessageShow: false,
        isGlobalMessageBoxShow: false,
        messageTitleDes: "",
        message: "",
        messageBoxSaveShow: false,
        tableData: [],
        count: 0,
        pageIndex: 1,
        pageSize: 20,

        detailsDisabled: false, //详情 如果为true代表禁用状态
        selectOptions: [
          {
            label: "正常/停用状态（全部）",
            value: null
          },
          {
            label: "正常",
            value: 1
          },
          {
            label: "禁用",
            value: 0
          }
        ],
        searchModel: {
          userName: "",
          status: null //正常/停用状态（全部）
        },
        newAccountModel: {
          userName: "",
          roleName: "",
          accountPhone: "",
          id: 0,
          roleCode: ""
        },
        permersion: {
          add: true,
          del: true,
          update: true,
          search: true
        },
        loading: false,
        dialogTitle: "",
        centerTitle: "",
        rules: {
          userName: [{
            required: true,
            message: "请输入账号",
            trigger: "blur"
          }],
          roleCode: [{
            required: true,
            message: "请选择角色",
            trigger: "change"
          }],
          accountPhone: [{
            required: true,
            trigger: "blur",
            message: "请输入手机号码"
          }]
        },
        addOrUpdateLoading: false,
        roleButtonList: [],
        checkedData: [],

        roleButtonList2: [],
        checkedData2: []
      }
    },
    created() {
      this.getAccountData()
      this.queryRole()
    },
    mounted() {
      this.userCode = sessionStorage.getItem("userCode")
    },
    methods: {
      async queryRole() {
        const data = await queryRole()
        this.userData = data.object
      },
      /**
       * 获取表格方法
       */
      async getAccountData(pageIndex = 1, pageSize = 20, tableInfo) {
        this.loading = true
        if (tableInfo) {
          const {
            userName,
            status
          } = tableInfo
          const {
            object
          } = await queryAccountPage({
            pageIndex,
            pageSize,
            userName,
            status
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        } else {
          const {
            object
          } = await queryAccountPage({
            pageIndex,
            pageSize
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        }
      },
      pagination(pageItem) {
        this.getAccountData(pageItem.page, pageItem.limit)
      },

      /**
       * 修改按钮
       */
      handlerEdit(row) {
        this.centerTitle = "编辑"
        this.$refs.ycDialog.dialogVisible = true
        this.$refs.loginFormRef?.clearValidate()
        this.detailsDisabled = false
        this.newAccountModel.userName = row.userName
        this.newAccountModel.roleCode = row.roleCode
        this.newAccountModel.accountPhone = row.accountPhone
        this.newAccountModel.id = row.id
      },
      /**
       * 重置按钮
       */
      async handlerReset({ id }) {
        this.$confirm("确定重置密码吗", "重置操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        }).then(async () => {
          const {
            message,
            status
          } = await ResetPassword({
            id
          })
          if (status == "200") {
            this.getAccountData()
            this.isGlobalMessageShow = true
            this.message = "success"
          }
        })
      },
      /**
       * 启用或者禁用按钮
       */
      async handlerStatus({ id, status }) {
        const confirmMessageMap = status == 1 ? "确定禁用吗" : "确定启用吗"
        this.$confirm(confirmMessageMap, "禁用/启用操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        }).then(async () => {
          const {
            message,
            status
          } = await deactivate({
            id
          })
          if (status == "200") {
            this.getAccountData()
            this.isGlobalMessageShow = true
            this.message = "success"
          }
        })
      },
      /**
       * 删除按钮
       */
      async handlerDelete({ id }) {
        this.$confirm("确定删除此用户吗", "删除操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          center: true
        }).then(async () => {
          const {
            message,
            status
          } = await deleteAccount({
            id
          })
          if (status == "200") {
            this.getAccountData()
            this.isGlobalMessageShow = true
            this.message = "success"
          }
        })
      },

      // 搜索按钮
      async searchClick() {
        this.getAccountData(1, 20, this.searchModel)
      },
      /**
       * 新建账户
       * */
      async handlerAccount() {
        this.centerTitle = "添加"
        this.detailsDisabled = false
        this.$refs.ycDialog.dialogVisible = true
        Object.keys(this.newAccountModel).forEach((item) => {
          this.newAccountModel[item] = ""
        })
        this.$refs.loginFormRef?.clearValidate()
      },
      dialogSave() {
        this.$refs.loginFormRef.validate(async (v) => {
          if (v) {
            if (this.detailsDisabled) {
              // 详情的确定
              this.$refs.ycDialog.dialogVisible = false
            } else if (this.newAccountModel.id) {
              const {
                userName,
                accountPhone,
                id,
                roleCode
              } =
                this.newAccountModel
              const {
                message,
                status
              } = await updateLAccount({
                userName,
                roleCode,
                accountPhone,
                id
              })
              if (status == 200) {
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
                this.$message.success(message)
              }
            } else {
              const {
                message,
                status
              } = await insertUser(this.newAccountModel)
              if (status == 200) {
                this.getAccountData(1, 20)
                this.$refs.ycDialog.dialogVisible = false
                this.$message.success(message)
              }
            }
          }
        })
      },


      handlerConfigMenu(row) {
        this.dialogTitle = "分配设备权限"

        this.userCode = row.userCode
        this.roleButtonList = []
        this.checkedData = []
        this.addOrUpdateLoading = false

        queryMenuListWithTitle({
          userCode: row.userCode
        }).then(res => {
          let tempArr = res.object || []
          this.roleButtonList = tempArr

          // 添加checkAll是否全选
          this.roleButtonList = this.roleButtonList.map((v) => ({
            ...v,
            checkAll: false
          }))
          this.roleButtonList.forEach((item) => {
            let newChild = item.menuList.filter((v) => {
              return v.check
            })
            if (newChild.length == item.menuList.length) {
              item.checkAll = true
            } else {
              item.checkAll = false
            }
          })
          tempArr.forEach((item) => {
            item.menuList.forEach((v) => {
              if (v.check) {
                this.checkedData.push(v)
              }
            })
          })
        })

        this.$refs.configDialog.dialogVisible = true
      },

      // 全选
      handleCheckAllListChange(val, item) {
        // 过滤掉没有选中的数据，item.child中不包含v时返回-1
        const filterArr = this.checkedData.filter((v) =>
          item.menuList.indexOf(v) == -1
        )
        this.checkedData = val ? filterArr.concat(item.menuList) : filterArr
      },
      // 是否全选
      itemIndeterminate(item) {
        return (
          item.menuList.some((v) => this.checkedData.indexOf(v) > -1) &&
          !item.menuList.every((v) => this.checkedData.indexOf(v) > -1)
        )
      },
      handleCheckedCitiesChange(val) {
        this.roleButtonList.forEach((item) => {
          item.checkAll = true
          item.menuList.forEach((v) => {
            if (!this.checkedData.includes(v)) {
              item.checkAll = false
            }
          })
        })
      },

      dialogSaveConfig() {
        this.addOrUpdateLoading = true
        let arr = this.checkedData.map(item => {
          return item.menuCode
        })
        setMenuAccountRelationShip({
          userCode: this.userCode,
          menuCodeStr: arr.toString()
        }).then(res => {
          if (res.status == 200) {
            this.$message.success(res.message)
            this.getAccountData()
            this.$refs.configDialog.dialogVisible = false
          }
          this.addOrUpdateLoading = false
        })
      },

      // 分配APP菜单
      handlerConfigAppMenu(row) {
        this.dialogTitle = "分配APP菜单"

        this.userCode = row.userCode
        this.roleButtonList2 = []
        this.checkedData2 = []
        this.addOrUpdateLoading = false

        queryMenuListWithTitleByApp({
          userCode: row.userCode
        }).then(res => {
          let tempArr = res.object || []
          this.roleButtonList2 = tempArr

          // 添加checkAll是否全选
          this.roleButtonList2 = this.roleButtonList2.map((v) => ({
            ...v,
            checkAll: false
          }))
          this.roleButtonList2.forEach((item) => {
            let newChild = item.menuList.filter((v) => {
              return v.check
            })
            if (newChild.length == item.menuList.length) {
              item.checkAll = true
            } else {
              item.checkAll = false
            }
          })
          tempArr.forEach((item) => {
            item.menuList.forEach((v) => {
              if (v.check) {
                this.checkedData2.push(v)
              }
            })
          })
        })

        this.$refs.configAppDialog.dialogVisible = true
      },
      // 全选
      handleCheckAllListChange2(val, item) {
        // 过滤掉没有选中的数据，item.child中不包含v时返回-1
        const filterArr = this.checkedData2.filter((v) =>
          item.menuList.indexOf(v) == -1
        )
        this.checkedData2 = val ? filterArr.concat(item.menuList) : filterArr
      },
      // 是否全选
      itemIndeterminate2(item) {
        return (
          item.menuList.some((v) => this.checkedData2.indexOf(v) > -1) &&
          !item.menuList.every((v) => this.checkedData2.indexOf(v) > -1)
        )
      },
      handleCheckedCitiesChange2(val) {
        this.roleButtonList2.forEach((item) => {
          item.checkAll = true
          item.menuList.forEach((v) => {
            if (!this.checkedData2.includes(v)) {
              item.checkAll = false
            }
          })
        })
      },

      dialogSaveConfigApp() {
        this.addOrUpdateLoading = true
        let arr = this.checkedData2.map(item => {
          return item.menuCode
        })
        setMenuAccountRelationShipByApp({
          userCode: this.userCode,
          menuCodeStr: arr.toString()
        }).then(res => {
          if (res.status == 200) {
            this.$message.success(res.message)
            this.getAccountData()
            this.$refs.configAppDialog.dialogVisible = false
          }
          this.addOrUpdateLoading = false
        })
      },
      /**
       * 刷新
       */
      refresh() {
        this.searchModel = {
          userName: "",
          status: null
        }
        this.getAccountData()
      },
      /**
       * globalMessage的知道按钮的方法
       * */
      receive() {
        this.isGlobalMessageShow = false
      },
      async messageBoxSave(show) {
        this.messageBoxSaveShow = show
      }
    }
  }
</script>

<style lang="scss" scoped>
  .status {
    display: inline-block;
    padding: 0 10px;
  }

  .title-container {
    display: flex;
    justify-content: flex-end;
    height: 60px;

    .search-content {
      margin-left: 20px;
      display: flex;
    }

    .addAccount {
      margin: 10px 20px;
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
  }

  .content {
    height: 600px;

    .drawer-title {
      font-weight: 400;
      font-size: 24px;
      color: #000000;
      text-align: center;
      padding: 36px 0;
    }

    .form {
      padding: 0 10px;
    }
  }

  .footer {
    height: 360px;
    display: flex;
    align-items: flex-end;
    // justify-content: st-end;
    padding: 5px 20px;
  }
</style>